package com.hooper.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hooper.common.JwtHelper;
import com.hooper.common.PageResult;
import com.hooper.emun.ResultCodeEnum;
import com.hooper.exception.BusinessException;
import com.hooper.mapper.SysUserMapper;
import com.hooper.model.dto.SysMenuDto;
import com.hooper.model.system.SysUser;
import com.hooper.model.vo.*;
import com.hooper.service.SysMenuService;
import com.hooper.service.SysUserService;
import com.hooper.util.MenuHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static com.hooper.constant.UserConstant.*;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/04/01/16:00
 */
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysMenuService  menuService;

    @Override
    public List<SysUser> getAllRoles() {
        return userMapper.selectAll();
    }

    @Override
    public PageResult<SysUser> pageByConditions(int currentPage, int pageSize, SysUserQueryVo queryVo) {
        PageHelper.startPage(currentPage, pageSize);
        List<SysUser> userList = userMapper.selectAllByVo(queryVo);
        PageInfo<SysUser> pageInfo = new PageInfo<>(userList);
        PageResult<SysUser> pageResult = new PageResult<>();
        pageResult.setCurrentPage(currentPage);
        pageResult.setPageSize(pageSize);
        pageResult.setData(pageInfo.getList());
        pageResult.setTotal((int) pageInfo.getTotal());
        return pageResult;
    }

    @Override
    public void saveUser(SysUser user) {
        // 校验参数
        userValidateCheck(user);
        // 密码加盐
        String password = user.getPassword() + EXTRA_SALT;
        // 密码加密
        String encryptedPwd = MD5Encoder.encode(password.getBytes());
        user.setPassword(encryptedPwd);
        userMapper.insert(user);
    }

    private void userValidateCheck(SysUser user) {
        if (user == null) {
            throw new RuntimeException("用户不能为空");
        }
        if (StringUtils.isEmpty(user.getUsername())) {
            throw new RuntimeException("用户名不能为空");
        }
        if (StringUtils.isEmpty(user.getPassword())) {
            throw new RuntimeException("密码不能为空");
        }
        if (StringUtils.isEmpty(user.getPhone()) || user.getPhone().length() != 11) {
            throw new RuntimeException("手机号码格式不正确");
        }
    }

    @Override
    public void updateUserById(SysUser newUser) {
        userValidateCheck(newUser);
        newUser.setUpdateTime(new Date());
        userMapper.updateById(newUser);
    }

    @Override
    public void delUserById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public void delBatchByIds(List<Long> ids) {
        userMapper.deleteBatchByIds(ids);
    }

    @Override
    public SysUser getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public void changeUserStatus(Long id, Integer status) {
        SysUser sysUser = userMapper.selectById(id);
        sysUser.setStatus(status.equals(1) ? 1 : 0);
        userMapper.updateById(sysUser);
    }

    @Override
    public String login(LoginVo loginVo) {
        String password = loginVo.getPassword();
        String username = loginVo.getUsername();
        if (StringUtils.isAnyBlank(password, username)) {
            throw new BusinessException(ResultCodeEnum.NULL_PARAM);
        }
        SysUser user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new BusinessException(ResultCodeEnum.USER_NOT_EXIST);
        }
        if (user.getStatus().equals(USER_STATUS_BANNED)) {
            throw new BusinessException(ResultCodeEnum.USER_BANNED);
        }
        // 密码加盐
        password = MD5Encoder.encode((password + EXTRA_SALT).getBytes());
        // 密码加密后校验
        if (!password.equals(user.getPassword())) {
            throw new BusinessException("密码错误！");
        }
        // 生成token
        return JwtHelper.createToken(user.getId(), user.getUsername());
    }

    @Override
    public Map<String, Object> getUserInfo(Long userId) {
        Map<String, Object> result = new HashMap<>();
        List<SysMenuDto> menuList = menuService.initMenuList(userId);
        // 将菜单列表转换为路由列表
        List<RouterVo> routers = MenuHelper.toRouter(MenuHelper.toTree(menuList));
        result.put("routers", routers);
        List<String> buttonNameList = menuService.selectButtonsByUserId(userId);
        log.info("-->routers: {}", routers);
        log.info("-->buttonNameList: {}", buttonNameList);
        result.put("buttons", buttonNameList);
        return result;
    }
}
